<?php


namespace app\backend\controller\v2;

use app\backend\validate\WebsiteValidate;
use app\BaseController;
use app\common\model\Website as WebsiteModel;
use think\exception\ValidateException;

class Website extends BaseController
{
    /**
     * 联系我们列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $model = new WebsiteModel();
        $data = $model->select();
        foreach ($data as &$v){
            if (!empty($v['wCode']))
                $v['wCode'] = env('APP.YUMING') . $v['wCode'];
            if (!empty($v['logo']))
                $v['logo'] = env('APP.YUMING') . $v['logo'];
        }
        return sucessMsg(200, '联系我们获取成功！', $data);
    }

    /**
     * 显示编辑资源表单页.
     *
     * @return \think\Response
     */
    public function edit()
    {
        $id = input('get.id/d');
        if (empty($id)) {
            return errMsg(422, 'id不能为空');
        }
        $data = WebsiteModel::where('id', $id)->find();
        if (!empty($data['wCode']))
            $data['wCode'] = env('APP.YUMING') . $data['wCode'];
        if (!empty($data['logo']))
            $data['logo'] = env('APP.YUMING') . $data['logo'];
        if (empty($data))
            return errMsg(422, '无效id');
        return sucessMsg(200, '获取成功！', $data);
    }

    /**
     * 保存更新的资源
     *
     * @param \think\Request $request
     * @param int $id
     * @return \think\Response
     */
    public function update()
    {
        $data = input();
        try {
            validate(WebsiteValidate::class)->scene('update')->check($data);
            if (empty($data['wCode'])) {
                return errMsg(400, '请上传二维码');
            }
            if (empty($data['logo'])) {
                return errMsg(400, '请上传公司logo');
            }
            if(strpos($data['wCode'],'.com') !== false){
                $data['wCode'] = substr($data['wCode'],strpos( $data['wCode'],"m")+2);
            }
            if(strpos($data['logo'],'.com') !== false){
                $data['logo'] = substr($data['logo'],strpos( $data['logo'],"m")+2);
            }
            $model = new WebsiteModel();
            $cate = $model->where('id', $data['id'])->find();
            if ($cate->save($data)) {
                return sucessMsg(200, '修改成功！');
            }
            return errMsg(500, '修改失败！');
        } catch (ValidateException $e) {
            return errMsg(400, $e->getError());
        }
    }
}